﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ArchivingDataModel;
using ArchivingDataWebForms.Helpers;
using Telerik.Web.UI;
using WebHelper.Handlers;
using WebHelper.Helpers;

namespace ArchivingDataWebForms.Pages.Folders
{
    public partial class ViewFolders : WebFormBase
    {
        protected string CutNodeID
        {
            get
            {
                return this.ViewState["CutNodeID"] == null ? null : this.ViewState["CutNodeID"].ToString();
            }
            set
            {
                this.ViewState["CutNodeID"] = value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                long? id = null;
                if (!string.IsNullOrEmpty(this.Request.QueryString[QueryStringParams.Folder_ID]))
                {
                    id = Convert.ToInt64(this.Request.QueryString[QueryStringParams.Folder_ID]);
                }
                this.getParents(id);
                //this.RadRibbonBar.SelectedTabIndex = this.RadRibbonBar.Tabs.Count - 1;
            }
        }
        protected void RadTreeViewFolder_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            using (ArchivingDataEntities ent = new ArchivingDataEntities())
            {
                e.Node.Nodes.Clear();
                long parentID = Convert.ToInt64(e.Node.Value);
                var childFolders = ent.Folders.Where(i => i.ParentFolder_ID == parentID && i.Is_RecycleBin == false).OrderBy(i => i.Folder_Order).ToArray();
                for (int i = 0; i < childFolders.Length; i++)
                {
                    string url = ImageEdittingHandler.GetUrl(childFolders[i].ImagePath, 32, 32, null, null, null, FlipType.None);
                    RadTreeNode Node = new RadTreeNode()
                    {
                        Text = childFolders[i].FolderName_Ar + " (" + this.getFilesNumber(ent, childFolders[i]) + ")",
                        Value = childFolders[i].Folder_ID.ToString(),
                        ExpandMode = TreeNodeExpandMode.ServerSide,
                        ImageUrl = url,
                    };
                    e.Node.Nodes.Add(Node);

                    long id = childFolders[i].Folder_ID;
                    //remove expand if no child
                    if (!ent.Folders.Any(k => k.ParentFolder_ID == id && k.Is_RecycleBin == false))
                    {
                        Node.Expanded = true;
                    }

                }

            }
        }
        protected void RadTreeViewFolder_ContextMenuItemClick(object sender, RadTreeViewContextMenuEventArgs e)
        {
            switch (e.MenuItem.Value)
            {
                case "1":
                    {
                        this.ShowWindow(WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/AddFolder.aspx"));
                        break;
                    }
                case "2":
                    {
                        this.ShowWindow(WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/AddFolder.aspx?" + QueryStringParams.Parent_ID + "=" + e.Node.Value));
                        break;
                    }
                case "3":
                    {
                        this.ShowWindow(WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/AddFolder.aspx?" + QueryStringParams.Folder_ID + "=" + e.Node.Value));
                        break;
                    }
                case "4":
                    {
                        try
                        {
                            using (ArchivingDataEntities ent = new ArchivingDataEntities())
                            {
                                long id = Convert.ToInt64(e.Node.Value);
                                var item = ent.Folders.FirstOrDefault(i => i.Folder_ID == id);
                                item.Is_RecycleBin = true;
                                ent.SaveChanges();
                                this.ShowNotification("تم نقال المجلد لسلة المحذوفات ", NotificationIconType.Ok);
                                e.Node.Remove();
                            }
                        }
                        catch (Exception er)
                        {
                            this.ShowNotification("حدث الخطا التالي اثناء النقل " + er.Message, NotificationIconType.Error);
                        }
                        break;
                    }
                case "5":
                    {
                        break;
                    }
                case "6":
                    {
                        break;
                    }
                case "7":
                    {
                        break;
                    }
                default:
                    {
                        break;
                    }

            }
        }
        protected void RadTreeViewFolder_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                //string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Files/Viewfiles.aspx?" + QueryStringParams.Folder_ID + "=" + this.RadTreeViewFolder.SelectedNode.Value).ToString();
                changeIframeUrl("", "");
            }
        }
        protected void RadRibbonBar_ButtonClick(object sender, RibbonBarButtonClickEventArgs e)
        {
            if (e.Button.CommandName.ToLower() == "ShowFiles".ToLower())
            {
                this.showFiles();
            }
            else if (e.Button.CommandName.ToLower() == "ShowProperties".ToLower())
            {
                this.showProperties();
            }
            else if (e.Button.CommandName.ToLower() == "createPrimaryFolder".ToLower())
            {
                this.createPrimaryFolder();
            }
            else if (e.Button.CommandName.ToLower() == "createSubFolder".ToLower())
            {
                this.createSubFolder();
            }
            else if (e.Button.CommandName.ToLower() == "ModifyFolder".ToLower())
            {
                this.modifyFolder();
            }
            else if (e.Button.CommandName.ToLower() == "FolderUP".ToLower())
            {
                this.movefolderUP();
            }
            else if (e.Button.CommandName.ToLower() == "FolderDown".ToLower())
            {
                this.MoveFolderDown();
            }
            else if (e.Button.CommandName.ToLower() == "CutFolder".ToLower())
            {
                this.cutFolder();
            }
            else if (e.Button.CommandName.ToLower() == "CopyFolder".ToLower())
            {
                this.CopyFolder();
            }
            else if (e.Button.CommandName.ToLower() == "Pastefolder".ToLower())
            {
                this.pasteFolder();
            }
            else if (e.Button.CommandName.ToLower() == "ToPrimaryFolder".ToLower())
            {
                this.convertToPrimary();
            }
            else if (e.Button.CommandName.ToLower() == "Network".ToLower())
            {
                this.importFoldersFromNetwork();
            }
            else if (e.Button.CommandName.ToLower() == "Export".ToLower())
            {
            }
            else if (e.Button.CommandName.ToLower() == "Scanner".ToLower())
            {
                this.importAttachmentsFromScanner();
            }
            else if (e.Button.CommandName.ToLower() == "BarCode".ToLower())
            {
            }

        }

        private void CopyFolder()
        {
            using (ArchivingDataEntities ent = new ArchivingDataEntities())
            {
                if (this.RadTreeViewFolder.SelectedNode != null)
                {
                    long id=Convert.ToInt64(this.RadTreeViewFolder.SelectedNode.Value);
                    var currentFolder = ent.Folders.Include("FilesType").FirstOrDefault(i => i.Folder_ID == id);
                  long newID=  this.CopyFolder(currentFolder, currentFolder.ParentFolder_ID, ent);
                  this.getParents(newID);
                }
            }
        }
        private long CopyFolder(Folder CurrentFolder, long? parentID, ArchivingDataEntities ent)
        {
            var newFolder = new Folder();
            newFolder.FolderName_Ar = CurrentFolder.FolderName_Ar;
            newFolder.FolderName_En = CurrentFolder.FolderName_En;
            newFolder.FolderNote_Ar = CurrentFolder.FolderNote_Ar;
            newFolder.FolderNote_En = CurrentFolder.FolderNote_En;
            newFolder.FilesType = ent.Folders.Include("FilesType").FirstOrDefault(i => i.Folder_ID == CurrentFolder.Folder_ID).FilesType;
            newFolder.Folder_Order = ent.Folders.Where(i => i.ParentFolder_ID == parentID).Count() + 1;
            newFolder.ParentFolder_ID = parentID;
            newFolder.Is_RecycleBin = false;
            newFolder.Folder_UniqueText = CurrentFolder.Folder_UniqueText + "_نسخة_Copy";
            ent.AddToFolders(newFolder);
            ent.SaveChanges();
            var childs = ent.Folders.Where(i => i.ParentFolder_ID == CurrentFolder.Folder_ID).ToList();
            foreach (var itemChild in childs)
            {
                this.CopyFolder(itemChild, newFolder.Folder_ID, ent);
            }
            return newFolder.Folder_ID;
        }


        protected void RadButtonSilverLightEnd_Click(object sender, EventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    long folderID = Convert.ToInt64(this.RadTreeViewFolder.SelectedNode.Value);

                    var file_ID = ent.Files.Where(i => i.Folder.Folder_ID == folderID).OrderByDescending(i => i.File_ID).FirstOrDefault().File_ID;
                    string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Files/AddFile.aspx?" + QueryStringParams.File_ID + "=" + file_ID).ToString();
                    this.changeIframeUrl(url, "تعديل الملف");
                }
            }
            catch(Exception er)
            {
                this.ShowNotification("حدث الخطا التالي", NotificationIconType.Error);
            }
        }
        protected void RadButtonRemoveCutnode_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.CutNodeID))
            {
                this.divCutNode.Visible = false;
                this.RadTreeViewFolder.FindNodeByValue(this.CutNodeID).Visible = true;
                this.CutNodeID = "";
            }
        }
        protected void ButtonRefreshTree_Click(object sender, EventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    long id = Convert.ToInt64(this.HiddenFieldRefreshTree.Value);
                    this.getParents(id);
                    this.RadWindowDefault.NavigateUrl = "";
                    this.RadWindowDefault.Title = "";
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي" + er.ToString(), NotificationIconType.Error);
            }
        }



        private void showFiles()
        {
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Files/ViewFiles.aspx?" + QueryStringParams.Folder_ID + "=" + this.RadTreeViewFolder.SelectedNode.Value).ToString();
                changeIframeUrl(url, "عرض الملفات");
            }
            else
            {
                this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
            }
        }
        private void showProperties()
        {
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/ViewFolderProperties.aspx?" + QueryStringParams.Folder_ID + "=" + this.RadTreeViewFolder.SelectedNode.Value).ToString();
                changeIframeUrl(url, "عرض الخصائص");
            }
            else
            {
                this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
            }
        }
        private void getParents(long? id)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    this.RadTreeViewFolder.Nodes.Clear();
                    var allfolders = ent.Folders.Where(i => i.Is_RecycleBin != true).ToArray();
                    var rootsFolders = allfolders.Where(i => i.ParentFolder_ID == null).OrderBy(i => i.Folder_Order).ToArray();

                    //add default folder
                    if (allfolders.Count() == 0)
                    {
                        ent.AddToFolders(new Folder
                        {
                            FolderName_Ar = "مجلد افتراضي",
                            FolderName_En = "Default folder",
                            FolderNote_Ar = "من فضلك قم بتغيير اسم المجلد",
                            FolderNote_En = "please change the name of the the folder",
                            Folder_Order = 1,
                            Is_RecycleBin = false,
                            ImagePath = CustomAppSettings.DefaultFolderImagePath
                        });
                        ent.SaveChanges();
                        //add new folder to allfolders and rootFolders
                        allfolders = new Folder[] { ent.Folders.FirstOrDefault() };
                        rootsFolders = new Folder[] { ent.Folders.FirstOrDefault() };
                    }
                    //fix folders swith no icons
                    var folderswithouIcons = ent.Folders.Where(i => string.IsNullOrEmpty(i.ImagePath));
                    if (folderswithouIcons.Count() > 0)
                    {
                        foreach (Folder item in folderswithouIcons)
                        {
                            item.ImagePath = CustomAppSettings.DefaultFolderImagePath;
                        }
                        ent.SaveChanges();
                    }


                    for (int i = 0; i < rootsFolders.Length; i++)
                    {
                        string url = ImageEdittingHandler.GetUrl(rootsFolders[i].ImagePath, 32, 32, null, null, null, FlipType.None);
                        RadTreeNode rootNode = new RadTreeNode()
                        {
                            Text = rootsFolders[i].FolderName_Ar + " ("+this.getFilesNumber(ent,rootsFolders[i])+")",
                            Value = rootsFolders[i].Folder_ID.ToString(),
                            ExpandMode = TreeNodeExpandMode.ServerSide,
                            ImageUrl = url,
                        };
                        this.RadTreeViewFolder.Nodes.Add(rootNode);

                        //remove expand if no child
                        if (!allfolders.Any(k => k.ParentFolder_ID == rootsFolders[i].Folder_ID))
                        {
                            rootNode.Expanded = true;
                        }
                    }

                    //select node from querystring
                    if (id.HasValue)
                    {
                        this.bindRequestNodeChain(allfolders,id.Value);
                    }

                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
            }
        }
        private void changeIframeUrl(string url, string title)
        {
            //this.iframedefault.Attributes["src"] = url;
            this.RadWindowDefault.NavigateUrl = url;
            this.RadWindowDefault.Title = title;
        }
        protected void bindRequestNodeChain(Folder[] allFoldsers,long id)
        {
            using (ArchivingDataEntities ent = new ArchivingDataEntities())
            {
                Folder currentFolder = allFoldsers.FirstOrDefault(i => i.Folder_ID == id);
                List<Folder> chain = new List<Folder>();
                while (currentFolder.ParentFolder_ID.HasValue)
                {
                    Folder parent = allFoldsers.FirstOrDefault(i => i.Folder_ID == currentFolder.ParentFolder_ID);
                    chain.Insert(0, parent);
                    currentFolder = parent;
                }
                //get chain of node
                for (int i = 0; i < chain.Count; i++)
                {
                    RadTreeNode node = this.RadTreeViewFolder.FindNodeByValue(chain[i].Folder_ID.ToString());

                    long parentID = chain[i].Folder_ID;
                    var childFolders = allFoldsers.Where(k => k.ParentFolder_ID == parentID && k.Is_RecycleBin == false).OrderBy(k => k.Folder_Order).ToArray();
                    for (int k = 0; k < childFolders.Length; k++)
                    {
                        string url = ImageEdittingHandler.GetUrl(childFolders[k].ImagePath, 32, 32, null, null, null, FlipType.None);
                        RadTreeNode childnode = new RadTreeNode()
                        {
                            Text = childFolders[k].FolderName_Ar + " (" + this.getFilesNumber(ent, childFolders[k]) + ")",
                            Value = childFolders[k].Folder_ID.ToString(),
                            ExpandMode = TreeNodeExpandMode.ServerSide,
                            ImageUrl = url,
                        };
                        node.Nodes.Add(childnode);

                        long childID = childFolders[k].Folder_ID;
                        //remove expand if no child
                        if (!allFoldsers.Any(z => z.ParentFolder_ID == childID && z.Is_RecycleBin == false))
                        {
                            childnode.Expanded = true;
                        }

                    }
                    node.Expanded = true;
                }
                var selectedNode = this.RadTreeViewFolder.FindNodeByValue(id.ToString());
                selectedNode.Selected = true;
                selectedNode.ExpandParentNodes();

                ////remove expand if no child
                //if (!allFoldsers.Any(k => k.ParentFolder_ID == id && k.Is_RecycleBin == false))
                //{
                //    selectedNode.Expanded = true;
                //}
            }
        }
        private void createPrimaryFolder()
        {
            string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/AddFolder.aspx").ToString();
            changeIframeUrl(url, "اضافة مجلد رئيسي");
        }
        private void createSubFolder()
        {
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/AddFolder.aspx?" + QueryStringParams.Parent_ID + "=" + this.RadTreeViewFolder.SelectedNode.Value).ToString();
                changeIframeUrl(url, "اضافة مجلد فرعي");
            }
            else
            {
                this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
            }
        }
        private void modifyFolder()
        {
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Folders/AddFolder.aspx?" + QueryStringParams.Folder_ID + "=" + this.RadTreeViewFolder.SelectedNode.Value).ToString();
                changeIframeUrl(url, "تعديل مجلد");
            }
            else
            {
                this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
            }
        }
        private void movefolderUP()
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (this.RadTreeViewFolder.SelectedNode != null)
                    {
                        if (this.RadTreeViewFolder.SelectedNode.Prev != null)
                        {
                            var node = this.RadTreeViewFolder.SelectedNode;
                            var node2 = this.RadTreeViewFolder.SelectedNode.Prev;
                            long id = Convert.ToInt64(node.Value);
                            long id2 = Convert.ToInt64(node2.Value);
                            var item = ent.Folders.FirstOrDefault(i => i.Folder_ID == id);
                            var item2 = ent.Folders.FirstOrDefault(i => i.Folder_ID == id2);
                            long oldOrder = item.Folder_Order.Value;
                            item.Folder_Order = item2.Folder_Order;
                            item2.Folder_Order = oldOrder;
                            ent.SaveChanges();
                            node.Remove();
                            node2.InsertBefore(node);
                        }
                    }
                    else
                    {
                        this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
                    }
                }
            }
            catch (Exception err)
            {
                this.ShowNotification("حدث الخطاء التالي :" + err.ToString(), NotificationIconType.Error);
            }
        }
        private void MoveFolderDown()
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (this.RadTreeViewFolder.SelectedNode != null)
                    {
                        if (this.RadTreeViewFolder.SelectedNode.Next != null)
                        {
                            var node = this.RadTreeViewFolder.SelectedNode;
                            var node2 = this.RadTreeViewFolder.SelectedNode.Next;
                            long id = Convert.ToInt64(node.Value);
                            long id2 = Convert.ToInt64(node2.Value);
                            var item = ent.Folders.FirstOrDefault(i => i.Folder_ID == id);
                            var item2 = ent.Folders.FirstOrDefault(i => i.Folder_ID == id2);
                            long oldOrder = item.Folder_Order.Value;
                            item.Folder_Order = item2.Folder_Order;
                            item2.Folder_Order = oldOrder;
                            ent.SaveChanges();
                            node.Remove();
                            node2.InsertAfter(node);
                        }
                    }
                    else
                    {
                        this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
                    }
                }
            }
            catch (Exception err)
            {
                this.ShowNotification("حدث الخطاء التالي :" + err.ToString(), NotificationIconType.Error);
            }
        }
        private void importFoldersFromNetwork()
        {
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                string url = WebHelper.Helpers.UrlHelper.GetCompleteUri("~/Pages/Import/Import.aspx?" + QueryStringParams.Folder_ID + "=" + this.RadTreeViewFolder.SelectedNode.Value).ToString();
                changeIframeUrl(url, "استيراد");
            }
            else
            {
                this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
            }
        }
        private void importAttachmentsFromScanner()
        {
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                //ScriptManager.RegisterStartupScript(this, this.GetType(), "scan", "startSilverLightScan(\"" + this.RadButtonSilverLightEnd.ClientID + "\",\"" + this.RadTreeViewFolder.SelectedNode.Value + "\",\"55555\")", true);
            }
        }
        private void cutFolder()
        {
            if (!string.IsNullOrEmpty(this.CutNodeID))
            {
                this.RadTreeViewFolder.FindNodeByValue(this.CutNodeID).Visible = true;
            }
            if (this.RadTreeViewFolder.SelectedNode != null)
            {
                this.divCutNode.Visible = true;
                this.RadButtonCutNode.Text = this.RadTreeViewFolder.SelectedNode.Text;
                this.RadTreeViewFolder.SelectedNode.Visible = false;
                this.CutNodeID = this.RadTreeViewFolder.SelectedNode.Value;
            }
            else
            {
                this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
            }
        }
        private void pasteFolder()
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (!string.IsNullOrEmpty(this.CutNodeID))
                    {
                        if (this.RadTreeViewFolder.SelectedNode != null)
                        {
                            long id = Convert.ToInt64(this.CutNodeID);
                            long parentID = Convert.ToInt64(this.RadTreeViewFolder.SelectedNode.Value);
                            var folder = ent.Folders.FirstOrDefault(i => i.Folder_ID == id);
                            folder.ParentFolder_ID = parentID;
                            folder.Folder_Order = ent.Folders.Where(i => i.ParentFolder_ID == parentID).Count() + 1;
                            ent.SaveChanges();
                            RadTreeNode node = this.RadTreeViewFolder.FindNodeByValue(this.CutNodeID);
                            node.Visible = true;
                            node.Remove();
                            this.RadTreeViewFolder.SelectedNode.Nodes.Add(node);
                            this.CutNodeID = "";
                            this.divCutNode.Visible = false;
                        }
                        else
                        {
                            this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
                        }
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي" + er.ToString(), NotificationIconType.Error);
            }
        }
        private void convertToPrimary()
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (this.RadTreeViewFolder.SelectedNode != null)
                    {
                        long id = Convert.ToInt64(this.RadTreeViewFolder.SelectedNode.Value);
                        var folder = ent.Folders.FirstOrDefault(i => i.Folder_ID == id);
                        if (folder.ParentFolder_ID != null)
                        {
                            folder.ParentFolder_ID = null;
                            folder.Folder_Order = ent.Folders.Count() + 1;
                            ent.SaveChanges();
                            RadTreeNode node= this.RadTreeViewFolder.SelectedNode;
                            node.Remove();
                            this.RadTreeViewFolder.Nodes.Add(node);
                        }
                    }
                    else
                    {
                        this.ShowNotification("من فضلك قم باختيار مجلد", NotificationIconType.Warning);
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي" + er.ToString(), NotificationIconType.Error);
            }
        }


        private int getFilesNumber(ArchivingDataEntities entities,Folder fold)
        {
            int totalcount= entities.Folders.Include("Files").FirstOrDefault(i => i.Folder_ID == fold.Folder_ID).Files.Count();
            var subFolders = entities.Folders.Include("Files").Where(i => i.ParentFolder_ID == fold.Folder_ID);
            foreach (var item in subFolders)
            {
                totalcount += this.getFilesNumber(entities, item);
            }
            return totalcount;
        }


    }
}